from wsgiref import headers

import requests
import os
import userAgentTools


def parse_http_url(temp_url):
    # 随机获取某个身份
    headers = userAgentTools.get_headers()
    # 爬
    response = requests.get(temp_url, headers=headers)
    texts = response.content.decode("utf-8")
    # print(texts)
    return texts


def get_hero():
    url = "https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js"
    res = requests.get(url).json()
    for hero in res['hero']:
        hero_id = hero['heroId']
        detail_line = 'https://game.gtimg.cn/images/lol/act/img/js/hero/' + hero_id + '.js'  # 字符串拼接

        get_skin(detail_line)


def get_skin(url):
    res = requests.get(url).json()
    for skin in res["skins"]:
        if not skin["mainImg"]:
            continue
        item = {}
        item["heroName"] = skin["heroName"]  # 英雄的名字
        item["skinName"] = skin["name"].replace("/", "_")
        item["skinImage"] = skin["mainImg"]  # 皮肤的图片链接
        print(item)
        save(item)


def save(item):
    # 构造一个目录
    hero_path = '.images/' + item['heroName'] + '/'
    if not os.path.exists(hero_path):  # 若目录不存在则创建目录
        os.makedirs(hero_path)
    res = requests.get(item["skinImage"])  # 发送图片请求
    with open(hero_path + item["skinName"] + ".png", "wb") as f:
        f.write(res.content)


if __name__ == "__main__":
    get_hero()
